package com.MRSyc.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSONObject;

import io.micrometer.core.instrument.util.StringUtils;

public class ClientUtils {
	
	private String access_token=null;
	HttpClient httpclient = HttpClients.createDefault();
	/**
	 * POST 请求
	 * 
	 * @param url    请求地址
	 * @param params 请求参数
	 * @param encode 编码格式
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public HttpResponse doPostMethod(String url, Map<String, String> params, String encode) {
		//HttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		if (params != null) {
			List<NameValuePair> form = new ArrayList<NameValuePair>();
			for (String name : params.keySet()) {
				form.add(new BasicNameValuePair(name, params.get(name)));
			}
			UrlEncodedFormEntity entity;
			try {
				entity = new UrlEncodedFormEntity(form, encode);
				httpPost.setEntity(entity);
				
				//httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
				return httpclient.execute(httpPost);
				/*
				 * if (response.getEntity() != null) {
				 * System.out.println(response.getStatusLine()); JSONObject obj =
				 * JSONObject.parseObject(streamToStr(response.getEntity().getContent(),
				 * "UTF-8")); return obj; }
				 */
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return null;
	}
	
	public HttpResponse doPost(String url, Map<String, String> params, String encode) {
		//HttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		if (params != null) {
			

			try {
				StringEntity entity= new StringEntity(params.get("json"),"utf-8");
				httpPost.setEntity(entity);
				httpPost.addHeader("Authorization","Bearer "+access_token);
				httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
				return httpclient.execute(httpPost);
				/*
				 * if (response.getEntity() != null) {
				 * System.out.println(response.getStatusLine()); JSONObject obj =
				 * JSONObject.parseObject(streamToStr(response.getEntity().getContent(),
				 * "UTF-8")); return obj; }
				 */
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return null;
	}

	/**
	 * GET 请求
	 * 
	 * @param url    请求地址
	 * @param params 请求参数
	 * @param encode 编码格式
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public HttpResponse doGetMethod(String url, Map<String, String> params, String encode) {
		
		// HttpPost httpPost = new HttpPost(url);
		
		if (params != null) {
			boolean param = true;
			for (String name : params.keySet()) {
					if (param) {
						url += "?" + name + "=" + params.get(name);
						param = false;
					} else {
						url += "&" + name + "=" + params.get(name);
					}
				
				

			}
			
			try {
				//httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
				HttpGet httpGet = new HttpGet(url);
				httpGet.addHeader("Authorization","Bearer "+access_token);
				return httpclient.execute(httpGet);

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

		return null;
	}

	public static String streamToStr(InputStream inputStream, String chartSet) {

		StringBuilder builder = new StringBuilder();

		try {

			BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, chartSet));

			String con;

			while ((con = br.readLine()) != null) {

				builder.append(con);

			}

			br.close();

			return builder.toString();

		} catch (Exception e) {

			e.printStackTrace();

		}

		return "";

	}

	/*
	 * 获取/刷新Token
	 */
	public String getToken(String url, Map<String, String> params) {
		String flg = null;
		HttpResponse response = doPostMethod(url, params, "UTF-8");
		if (response != null) {
			System.out.println("code = " + response.getStatusLine().getStatusCode());
			if (response.getStatusLine().getStatusCode() == 200 && response.getEntity() != null) {
				JSONObject obj;
				try {
					obj = JSONObject.parseObject(streamToStr(response.getEntity().getContent(), "UTF-8"));
					String token = obj.getString("access_token");
					
					if (StringUtils.isNotEmpty(token))
						access_token = token;

				} catch (UnsupportedOperationException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		}
		return flg;
	}

	/*
	 * 试剂入库单查询
	 */
	public Map<String, Object> getInboundList(String url, Map<String, String> params) {
		Map<String, Object> map = new HashMap<>();
		HttpResponse response = doGetMethod(url, params, "UTF-8");
		map.put("code", response.getStatusLine().getStatusCode());
		if (response != null && response.getEntity() != null) {
			try {
				map.put("result", streamToStr(response.getEntity().getContent(), "UTF-8"));
			} catch (UnsupportedOperationException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return map;
	}
	
	/*
	 * 创建试剂出库单
	 */
	public Map<String, Object> createOutboundList(String url, Map<String, String> params) {
		Map<String, Object> map = new HashMap<>();
		HttpResponse response = doPost(url, params, "UTF-8");
		map.put("code", response.getStatusLine().getStatusCode());
		if (response != null && response.getEntity() != null) {
			try {
				map.put("result", streamToStr(response.getEntity().getContent(), "UTF-8"));
			} catch (UnsupportedOperationException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		return map;
	}

}
